<template>
  <el-drawer
    :title="
      drawer.type === 'edit'
        ? '编辑模版'
        : drawer.type === 'new'
        ? '新增模版'
        : '模版详情'
    "
    :visible.sync="drawer.show"
    size="60%"
    custom-class="add-drawer"
  >
    <!-- <div style="padding: 0 20px;margin-bottom: 20px;">
            <el-divider></el-divider>
            <el-form :inline="true" :model="queryData" size="small" ref="queryData" :rules="queryDataRules">
                <el-form-item label="油企名称" v-if="authUser" prop="enterpriseId">
                    <el-select placeholder="请选择油企" v-model="queryData.enterpriseId" :disabled="drawer.type === 'read'">
                        <el-option v-for="item in enterpriseList" :key="item.enterpriseId" :label="item.enterpriseName"
                            :value="item.enterpriseId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="推送渠道" prop="pushChannel">
                    <el-select v-model="queryData.pushChannel" placeholder="请选择推送渠道" :disabled="drawer.type === 'read'">
                        <el-option v-for="item in channelList" :key="item.value" :label="item.key"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </div> -->
    <div style="padding: 0 20px; margin-bottom: 30px">
      <!-- <p>消息配置</p> -->
      <el-divider></el-divider>
      <div class="title">
        模板消息仅支持已认证服务号“IT科技/互联网|电子商务->交通工具/汽车相关”类目，请登录<a
          href="https://mp.weixin.qq.com/"
          target="_blank"
          >”公众平台“</a
        >，左侧菜单栏”广告与服务“-”模板消息“中添加
      </div>

      <el-form
        ref="rechargeRef"
        :model="rechargeForm"
        :rules="rechargeRules"
        label-width="150px"
      >
        <el-form-item class="t" label="充值成功通知" prop="templateId">
          <el-input
            class="input-style"
            v-model="rechargeForm.templateId"
            placeholder="模版ID从公众平台获取,必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateUrl">
          <el-input
            class="input-style"
            v-model="rechargeForm.templateUrl"
            placeholder="跳转链接,非必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateContent">
          <customTemplateTag
            ref="rechargeTag"
            :templateTags="rechargeTemplateTags"
            title="关键词:"
          />
        </el-form-item>
      </el-form>

      <el-form
        ref="successRef"
        :model="successForm"
        :rules="successRules"
        label-width="150px"
      >
        <el-form-item label="加油成功通知" prop="templateId">
          <el-input
            class="input-style"
            v-model="successForm.templateId"
            placeholder="模版ID从公众平台获取,必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateUrl">
          <el-input
            class="input-style"
            v-model="successForm.templateUrl"
            placeholder="跳转链接,非必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateContent">
          <customTemplateTag
            ref="successTag"
            :templateTags="successTemplateTags"
            title="关键词:"
          />
        </el-form-item>
      </el-form>

      <el-form
        ref="priceRef"
        :model="priceForm"
        :rules="priceRules"
        label-width="150px"
      >
        <el-form-item label="商品调价通知" prop="templateId">
          <el-input
            class="input-style"
            v-model="priceForm.templateId"
            placeholder="模版ID从公众平台获取,必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateUrl">
          <el-input
            class="input-style"
            v-model="priceForm.templateUrl"
            placeholder="跳转链接,非必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateContent">
          <customTemplateTag
            ref="priceTag"
            :templateTags="priceTemplateTags"
            title="关键词:"
          />
        </el-form-item>
      </el-form>

      <el-form
        ref="couponRef"
        :model="couponForm"
        :rules="couponRules"
        label-width="150px"
      >
        <el-form-item label="优惠券发放通知" prop="templateId">
          <el-input
            class="input-style"
            v-model="couponForm.templateId"
            placeholder="模版ID从公众平台获取,必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateUrl">
          <el-input
            class="input-style"
            v-model="couponForm.templateUrl"
            placeholder="跳转链接,非必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateContent">
          <customTemplateTag
            ref="couponTag"
            :templateTags="couponTemplateTags"
            title="关键词:"
          />
        </el-form-item>
      </el-form>

      <el-form
        ref="couponActivityRef"
        :model="couponActivityForm"
        :rules="couponnActivityRules"
        label-width="150px"
      >
        <el-form-item label="优惠活动通知" prop="templateId">
          <el-input
            class="input-style"
            v-model="couponActivityForm.templateId"
            placeholder="模版ID从公众平台获取,必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateUrl">
          <el-input
            class="input-style"
            v-model="couponActivityForm.templateUrl"
            placeholder="跳转链接,非必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateContent">
          <customTemplateTag
            ref="couponActivityTag"
            :templateTags="couponActivityTemplateTags"
            title="关键词:"
          />
        </el-form-item>
      </el-form>

      <el-form
        ref="refundNoticeRef"
        :model="refundNoticeForm"
        :rules="refundNoticeRules"
        label-width="150px"
      >
        <el-form-item label="退款通知" prop="templateId">
          <el-input
            class="input-style"
            v-model="refundNoticeForm.templateId"
            placeholder="模版ID从公众平台获取,必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateUrl">
          <el-input
            class="input-style"
            v-model="refundNoticeForm.templateUrl"
            placeholder="跳转链接,非必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateContent">
          <customTemplateTag
            ref="refundNoticeTag"
            :templateTags="couponActivityRefundNotice"
            title="关键词:"
          />
        </el-form-item>
      </el-form>

      <el-form
        ref="changeIntegralRef"
        :model="changeIntegralForm"
        :rules="changeIntegralRules"
        label-width="150px"
      >
        <el-form-item label="积分变动通知" prop="templateId">
          <el-input
            class="input-style"
            v-model="changeIntegralForm.templateId"
            placeholder="模版ID从公众平台获取,必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateUrl">
          <el-input
            class="input-style"
            v-model="changeIntegralForm.templateUrl"
            placeholder="跳转链接,非必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateContent">
          <customTemplateTag
            ref="changeIntegralTag"
            :templateTags="couponActivityChangeIntegral"
            title="关键词:"
          />
        </el-form-item>
      </el-form>

      <!-- <el-form
        ref="fleetcardRef"
        :model="fleetcardForm"
        :rules="fleetcardRules"
        label-width="150px"
      >
        <el-form-item label="车队卡消费通知" prop="templateId">
          <el-input
            class="input-style"
            v-model="fleetcardForm.templateId"
            placeholder="模版ID从公众平台获取,必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateUrl">
          <el-input
            class="input-style"
            v-model="fleetcardForm.templateUrl"
            placeholder="跳转链接,非必填"
            :disabled="drawer.type === 'read'"
          ></el-input>
        </el-form-item>
        <el-form-item prop="templateContent">
          <customTemplateTag
            ref="fleetcardTag"
            :templateTags="fleetcardTemplateTags"
            title="关键词:"
          />
        </el-form-item>
      </el-form> -->
    </div>
    <div style="text-align: right; padding: 0 20px; margin-bottom: 20px">
      <el-button @click="handleClone">取消</el-button>
      <el-button
        v-if="drawer.type === 'edit'"
        type="primary"
        @click="handleSubmit('edit')"
        >提交</el-button
      >
      <el-button
        v-if="drawer.type === 'new'"
        type="primary"
        @click="handleSubmit('add')"
        >提交</el-button
      >
    </div>
  </el-drawer>
</template>
<script>
import customTemplateTag from "@/components/customTemplateTag";
import {
  wxMessageTemplateAdd,
  wxMessageTemplateEdit,
} from "@/api/message/template-msg";

export default {
  components: { customTemplateTag },
  props: {
    parm: {
      type: Object,
      default: null,
    },
  },
  data() {
    let validateRecharge = (rule, value, callback) => {
      let rechargeTag = this.$refs.rechargeTag.getTags();
      if (rechargeTag.length === 0) {
        callback(new Error("请选择关键词"));
        return;
      }
      callback();
    };
    let validateSuccess = (rule, value, callback) => {
      let successTag = this.$refs.successTag.getTags();
      if (successTag.length === 0) {
        callback(new Error("请选择关键词"));
        return;
      }
      callback();
    };
    let validatePrice = (rule, value, callback) => {
      let priceTag = this.$refs.priceTag.getTags();
      if (priceTag.length === 0) {
        callback(new Error("请选择关键词"));
        return;
      }
      callback();
    };
    let validateCoupon = (rule, value, callback) => {
      let couponTag = this.$refs.couponTag.getTags();
      if (couponTag.length === 0) {
        callback(new Error("请选择关键词"));
        return;
      }
      callback();
    };
    let validateCouponActivity = (rule, value, callback) => {
      let couponActivityTag = this.$refs.couponActivityTag.getTags();
      if (couponActivityTag.length === 0) {
        callback(new Error("请选择关键词"));
        return;
      }
      callback();
    };
    let validateRefundNotice = (rule, value, callback) => {
      let refundNoticeTag = this.$refs.refundNoticeTag.getTags();
      if (refundNoticeTag.length === 0) {
        callback(new Error("请选择关键词"));
        return;
      }
      callback();
    };
    let validateChangeIntegral = (rule, value, callback) => {
      let changeIntegralTag = this.$refs.changeIntegralTag.getTags();
      if (changeIntegralTag.length === 0) {
        callback(new Error("请选择关键词"));
        return;
      }
      callback();
    };
    // let validateFleetcard = (rule, value, callback) => {
    //   let fleetcardTag = this.$refs.fleetcardTag.getTags();
    //   if (fleetcardTag.length === 0) {
    //     callback(new Error("请选择关键词"));
    //     return;
    //   }
    //   callback();
    // };

    return {
      drawer: {
        show: this.parm ? this.parm.drawerShow : false,
        type: this.parm ? this.parm.drawerType : "read", // edit || read || new
      },
      enterpriseList: this.parm ? this.parm.enterpriseList : [],
      channelList: this.parm ? this.parm.channelList : [],
      msgData: this.parm ? this.parm.msgData : {},
      rechargeTemplateTags: [
        "充值卡号",
        "充值金额",
        "赠送金额",
        "余额",
        "充值时间",
      ],
      successTemplateTags: [
        "油站名称",
        "油品名称",
        "付款明细",
        "钱包余额",
        "消费时间",
      ],
      priceTemplateTags: ["操作类型", "操作金额", "时间"],
      couponTemplateTags: ["油站名称", "优惠券名称"],
      couponActivityTemplateTags: ["活动内容"],
      couponActivityRefundNotice: [
        "油站名称",
        "退款类型",
        "退款金额",
        "退款时间",
      ],
      couponActivityChangeIntegral: [
        "油站名称",
        "变动时间",
        "积分变动",
        "积分余额",
      ],
      // fleetcardTemplateTags: [
      //   "持卡人",
      //   "油站",
      //   "实付金额",
      //   "账户余额",
      //   "消费时间",
      // ],
      queryData: {
        enterpriseId: this.parm ? this.parm.enterpriseId : "",
        pushChannel: this.parm ? this.parm.pushChannel : "",
      },
      priceForm: {
        templateType: 4,
      },
      rechargeForm: {
        templateType: 3,
      },
      successForm: {
        templateType: 1,
      },
      couponForm: {
        templateType: 5,
      },
      couponActivityForm: {
        templateType: 6,
      },
      refundNoticeForm: {
        templateType: 7,
      },
      changeIntegralForm: {
        templateType: 8,
      },
      // fleetcardForm: {
      //   templateType: 9,
      // },
      rechargeRules: {
        templateId: [
          { required: true, message: "请输入模版id", trigger: "blur" },
        ],
        templateContent: [{ validator: validateRecharge, trigger: "change" }],
      },
      successRules: {
        templateId: [
          { required: true, message: "请输入模版id", trigger: "blur" },
        ],
        templateContent: [{ validator: validateSuccess, trigger: "change" }],
      },
      priceRules: {
        templateId: [
          { required: true, message: "请输入模版id", trigger: "blur" },
        ],
        templateContent: [{ validator: validatePrice, trigger: "change" }],
      },
      couponRules: {
        templateId: [
          { required: true, message: "请输入模版id", trigger: "blur" },
        ],
        templateContent: [{ validator: validateCoupon, trigger: "change" }],
      },
      couponnActivityRules: {
        templateId: [
          { required: true, message: "请输入模版id", trigger: "blur" },
        ],
        templateContent: [
          { validator: validateCouponActivity, trigger: "change" },
        ],
      },
      queryDataRules: {
        enterpriseId: [
          { required: true, message: "请选择油企", trigger: "change" },
        ],
        pushChannel: [
          { required: true, message: "请选择推送渠道", trigger: "change" },
        ],
      },
      refundNoticeRules: {
        templateId: [
          { required: true, message: "请输入模版id", trigger: "blur" },
        ],
        templateContent: [
          { validator: validateRefundNotice, trigger: "change" },
        ],
      },
      changeIntegralRules: {
        templateId: [
          { required: true, message: "请输入模版id", trigger: "blur" },
        ],
        templateContent: [
          { validator: validateChangeIntegral, trigger: "change" },
        ],
      },
      // fleetcardRules: {
      //   templateId: [
      //     { required: true, message: "请输入模版id", trigger: "blur" },
      //   ],
      //   templateContent: [{ validator: validateFleetcard, trigger: "change" }],
      // },
    };
  },
  methods: {
    handleSubmit(key) {
      // console.log(this.couponForm);
      // const form1 = new Promise((resolve, reject) => {
      //     this.$refs['queryData'].validate(valid => {
      //         if (valid) resolve()
      //     })
      // })
      const form2 = new Promise((resolve, reject) => {
        this.$refs["rechargeRef"].validate((valid) => {
          if (valid) resolve();
        });
      });
      const form3 = new Promise((resolve, reject) => {
        this.$refs["successRef"].validate((valid) => {
          if (valid) resolve();
        });
      });
      const form4 = new Promise((resolve, reject) => {
        this.$refs["priceRef"].validate((valid) => {
          if (valid) resolve();
        });
      });
      const form5 = new Promise((resolve, reject) => {
        this.$refs["couponRef"].validate((valid) => {
          if (valid) resolve();
        });
      });
      const form6 = new Promise((resolve, reject) => {
        this.$refs["couponActivityRef"].validate((valid) => {
          if (valid) resolve();
        });
      });
      const form7 = new Promise((resolve, reject) => {
        this.$refs["refundNoticeRef"].validate((valid) => {
          if (valid) resolve();
        });
      });
      const form8 = new Promise((resolve, reject) => {
        this.$refs["changeIntegralRef"].validate((valid) => {
          if (valid) resolve();
        });
      });
      // const form9 = new Promise((resolve, reject) => {
      //   this.$refs["fleetcardRef"].validate((valid) => {
      //     if (valid) resolve();
      //   });
      // });

      Promise.all([
        form2,
        form3,
        form4,
        form5,
        form6,
        form7,
        form8,
        // form9,
      ]).then(() => {
        let rechargeTag = this.$refs.rechargeTag.getTags();
        let successTag = this.$refs.successTag.getTags();
        let priceTag = this.$refs.priceTag.getTags();
        let couponTag = this.$refs.couponTag.getTags();
        let couponActivityTag = this.$refs.couponActivityTag.getTags();
        let refundNoticeTag = this.$refs.refundNoticeTag.getTags();
        let changeIntegralTag = this.$refs.changeIntegralTag.getTags();
        // let fleetcardTag = this.$refs.fleetcardTag.getTags();
        this.rechargeForm.templateContent = rechargeTag.join(",");
        this.successForm.templateContent = successTag.join(",");
        this.priceForm.templateContent = priceTag.join(",");
        this.couponForm.templateContent = couponTag.join(",");
        this.couponActivityForm.templateContent = couponActivityTag.join(",");
        this.refundNoticeForm.templateContent = refundNoticeTag.join(",");
        this.changeIntegralForm.templateContent = changeIntegralTag.join(",");
        // this.fleetcardForm.templateContent = fleetcardTag.join(",");
        let wxMessageTemplateForm = {
          enterpriseId: this.presentEnterprise.enterpriseId,
          pushChannel: 1,
          wxTemplateContentList: [],
        };
        wxMessageTemplateForm.wxTemplateContentList.push(this.rechargeForm);
        wxMessageTemplateForm.wxTemplateContentList.push(this.successForm);
        wxMessageTemplateForm.wxTemplateContentList.push(this.priceForm);
        wxMessageTemplateForm.wxTemplateContentList.push(this.couponForm);
        wxMessageTemplateForm.wxTemplateContentList.push(
          this.couponActivityForm
        );
        wxMessageTemplateForm.wxTemplateContentList.push(this.refundNoticeForm);
        wxMessageTemplateForm.wxTemplateContentList.push(
          this.changeIntegralForm
        );
        // wxMessageTemplateForm.wxTemplateContentList.push(this.fleetcardForm);

        if (key === "add") {
          wxMessageTemplateAdd(wxMessageTemplateForm).then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.msg);
              this.$emit("success-data");
              this.drawer.show = false;
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          wxMessageTemplateEdit(wxMessageTemplateForm).then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.msg);
              this.$emit("success-data");
              this.drawer.show = false;
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    handleClone() {
      this.drawer.show = false;
    },
    format(data) {
      if (data) {
        this.queryData.enterpriseId = data.enterpriseId;
        this.queryData.pushChannel = data.pushChannel;
        data.wxTemplateContentList.forEach((item) => {
          if (item.templateType === 3) {
            this.rechargeForm = item;
            this.$nextTick(() => {
              this.$refs.rechargeTag.setTags(
                this.rechargeForm.templateContent.split(",")
              );
            });
          } else if (item.templateType === 1) {
            this.successForm = item;
            this.$nextTick(() => {
              this.$refs.successTag.setTags(
                this.successForm.templateContent.split(",")
              );
            });
          } else if (item.templateType === 4) {
            this.priceForm = item;
            this.$nextTick(() => {
              this.$refs.priceTag.setTags(
                this.priceForm.templateContent.split(",")
              );
            });
          } else if (item.templateType === 5) {
            this.couponForm = item;
            this.$nextTick(() => {
              this.$refs.couponTag.setTags(
                this.couponForm.templateContent.split(",")
              );
            });
          } else if (item.templateType === 6) {
            this.couponActivityForm = item;
            this.$nextTick(() => {
              this.$refs.couponActivityTag.setTags(
                this.couponActivityForm.templateContent.split(",")
              );
            });
          } else if (item.templateType === 7) {
            this.refundNoticeForm = item;
            this.$nextTick(() => {
              this.$refs.refundNoticeTag.setTags(
                this.refundNoticeForm.templateContent.split(",")
              );
            });
          } else if (item.templateType === 8) {
            this.changeIntegralForm = item;
            this.$nextTick(() => {
              this.$refs.changeIntegralTag.setTags(
                this.changeIntegralForm.templateContent.split(",")
              );
            });
          }
          // else if (item.templateType === 9) {
          //   this.fleetcardForm = item;
          //   this.$nextTick(() => {
          //     this.$refs.fleetcardTag.setTags(
          //       this.fleetcardForm.templateContent.split(",")
          //     );
          //   });
          // }
        });
      } else {
        // this.$nextTick(() => {
        //     this.$refs["queryData"].resetFields()
        // })
        // this.queryData.enterpriseId = ''
        // this.queryData.pushChannel = ''
        this.rechargeForm = {
          templateType: 3,
        };
        this.$nextTick(() => {
          this.$refs.rechargeTag.setTags([]);
        });
        this.successForm = {
          templateType: 1,
        };
        this.$nextTick(() => {
          this.$refs.successTag.setTags([]);
        });
        this.priceForm = {
          templateType: 4,
        };
        this.$nextTick(() => {
          this.$refs.priceTag.setTags([]);
        });
        this.couponForm = {
          templateType: 5,
        };
        this.$nextTick(() => {
          this.$refs.couponTag.setTags([]);
        });
        this.couponActivityForm = {
          templateType: 6,
        };
        this.$nextTick(() => {
          this.$refs.couponActivityTag.setTags([]);
        });
        this.refundNoticeForm = {
          templateType: 7,
        };
        this.$nextTick(() => {
          this.$refs.refundNoticeTag.setTags([]);
        });
        this.changeIntegralForm = {
          templateType: 8,
        };
        this.$nextTick(() => {
          this.$refs.changeIntegralTag.setTags([]);
        });
        // this.fleetcardForm = {
        //   templateType: 9,
        // };
        // this.$nextTick(() => {
        //   this.$refs.fleetcardTag.setTags([]);
        // });
      }
    },
  },
  watch: {
    parm(newValue) {
      this.drawer.show = newValue.drawerShow;
      this.drawer.type = newValue.drawerType;
      this.enterpriseList = newValue.enterpriseList;
      this.channelList = newValue.channelList;
      this.msgData = newValue.msgData;
      this.format(this.msgData);
    },
  },
  computed: {
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.title {
  color: #05a6f0;
  text-align: center;
  border: 1px solid #ccc;
  padding: 14px 0;
  border-radius: 10px;
  margin-bottom: 12px;
}

a {
  list-style: none;
  color: #0000ff !important;
}

.form-box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.form {
  width: 60%;
}

.input-style {
  width: 90%;
  margin-bottom: 12px;
}

::v-deep .el-form-item__label::before {
  content: "*";
  color: red;
  margin-right: 5px;
}

::v-deep .add-drawer {
  overflow-y: auto;
}

::v-deep .el-drawer__header {
  margin-bottom: 0 !important;
}
</style>
